/*
 * Solo - A small and beautiful blogging system written in Java.
 * Copyright (c) 2010-present, b3log.org
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
/**
 * @fileoverview util and every page should be used.
 *
 * @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
 * @version 0.3.0.0, Dev 17, 2018
 */

/**
 * @description 皮肤脚本
 * @static
 */
var Skin = {
    _initCommon: function ($goTop) {
        $(window).scroll(function () {
            if ($(window).scrollTop() > 125) {
                $goTop.show()
            } else {
                $goTop.hide()
            }

            if ($('.side .article__toc').length > 0 && $(window).width() > 768) {
                if ($(window).scrollTop() > 50) {
                    $('.side').css('position', 'fixed')
                } else {
                    $('.side').css('position', 'initial')
                }
            }
        })
    },
    _initAnimation: function () {
        if (!('IntersectionObserver' in window)) {
            $('.item').addClass('item--active')
            return false
        }

        if (window.imageIntersectionObserver) {
            window.imageIntersectionObserver.disconnect()
            $('.item').each(function () {
                window.imageIntersectionObserver.observe(this)
            })
        } else {
            window.imageIntersectionObserver = new IntersectionObserver(
                function (entries) {
                    entries.forEach(function (entrie) {
                        if (typeof entrie.isIntersecting === 'undefined'
                            ? entrie.intersectionRatio !== 0 : entrie.isIntersecting) {
                            $(entrie.target).addClass('item--active')
                        } else {
                            if ($(entrie.target).closest('.side').length === 1 ||
                                $(entrie.target).closest('#articlePage').length === 1 ||
                                $(entrie.target).outerHeight() > 768) {
                                return
                            }
                            $(entrie.target).removeClass('item--active')
                        }
                    })
                })
            $('.item').each(function () {
                window.imageIntersectionObserver.observe(this)
            })
        }
    },
    init: function () {
        Util.initPjax(function () {
            Skin._initAnimation()
        })

        Skin._initAnimation()

        this._initCommon($('.icon__up'))

        $('.header__nav a, .header__m a').each(function () {
            if (this.href === location.href) {
                this.className = 'current'
            }
        }).click(function () {
            $('.header__nav a, .header__m a').removeClass('current')
            this.className = 'current'
            $('.header__m .module__list').hide()
        })

        $('.header__logo').click(function () {
            $('.header__nav a, .header__m a').removeClass('current')
        })
    },
    _initArticleCommon: function () {
        if ($(window).width() > 768) {
            if ($('.article__toc li').length === 0) {
                $('.side').css({
                    height: 'auto',
                    position: 'initial',
                })
                return
            }

            $('#articlePage').width($('.main').width() - 310)
            $('.side').css({
                right: ($(window).width() - $('.main').width()) / 2,
                position: 'fixed',
                overflow: 'auto',
                height: $(window).height() - 30,
                top: 30,
            })
            $(window).scroll()
            $('.side').scrollTop(0)
        }
    },
    initArticle: function () {
        this._initArticleCommon()

        setTimeout(function () {
            if ($('#externalRelevantArticlesWrap li').length === 0) {
                $('#externalRelevantArticlesWrap').next().remove()
                $('#externalRelevantArticlesWrap').remove()
            }

            if ($('#relevantArticlesWrap li').length === 0) {
                $('#relevantArticlesWrap').prev().remove()
                $('#relevantArticlesWrap').remove()
            }

            if ($('#randomArticlesWrap li').length === 0) {
                $('#randomArticlesWrap').prev().remove()
                $('#randomArticlesWrap').remove()
            }
        }, 1000)
    },
}
Skin.init()
waypointsInit()

function waypointsInit() {

    window.onscroll = function () {
        //为了保证兼容性，这里取两个值，哪个有值取哪一个
        //scrollTop就是触发滚轮事件时滚轮的高度
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var className = document.getElementById("headerContain").className;
        var footerClassName = document.getElementById("footerContain").className;
       var footerRects= document.getElementById("footerContain").getClientRects();
       console.log("scrollTop")
       console.log(scrollTop)
        console.log("style")
        console.log(document.getElementById("footerContain").style);
       console.log("clientHeight")
        console.log(document.body.clientHeight);
        console.log("offsetHeight")
        console.log( document.body.offsetHeight);
        console.log("scrollHeight")
        console.log(document.body.scrollHeight);
        console.log("style.top")
        console.log(document.getElementById("footerContain").style.top);
        console.log("footerRects[0].top")
       console.log(footerRects[0].top);
        console.log("window.screen.height");
       console.log(window.screen.height);
       if(footerRects[0].top>window.screen.height){
           if(className.indexOf("animationon")!='-1'){
               document.getElementById("footerContain").className='animated from-bottom '
           }
       }else{
           if(className.indexOf("animationon")=='-1'){
               document.getElementById("footerContain").className='animated from-bottom animationon'
           }
       }
        if(scrollTop>455){
            if(className.indexOf("animationon")!='-1'){
                document.getElementById("headerContain").className='animated from-bottom '
            }
        }else{
            if(className.indexOf("animationon")=='-1'){
                document.getElementById("headerContain").className='animated from-bottom animationon'
            }
        }

    }
    /* $('#headerContain').waypoint(function(direction) {
       $(this).addClass('animation-on');
     });

     $('#pjax').waypoint(function(direction) {
       $('#headerContain').toggleClass('animation-on');
     });*/

}



//立即执行函数

//!的作用是告诉javascript引擎这是一个函数表达式，不是函数声明，()、！、+、-等运算符都能实现这个作用，不过()是最安全的

//在!function(){}后面加上()会立即调用这个函数

//这样做可以模仿一个私有作用域，这样html文件引用多个js文件时便不会造成变量冲突

!function () {

    var colorArr=[
        '#000000',
        '#FFFFFF','#FAFFF0','#FFFFCD','#FFFF00','#FF9912','#FF8000','#802A2A','#BC8F8F','#A020F0','#DA70D6','#00C78C','#191970'
        ,'#0000FF','#6B8E23','#228B22','#082E54','#00FF00','#990033','#FF00FF','#FFC0CB','#FF6347','#FF0000','#F5F5F5','#808A87',
        '#666666'
    ]
    function  getColorRamdom(){
        return colorArr[Math.floor(Math.random()*(colorArr.length))]
    }

//canvas元素相关
//创建canvas元素，并设置canvas元素的id
    var canvas = document.createElement("canvas"),
        context = canvas.getContext("2d"),
        attr = getAttr();
    console.log(attr)
//设置创建的canvas的相关属性

    canvas.id = "c_n" + attr.length;

    canvas.style.cssText = "position:fixed;top:0;left:0;z-index:" + attr.z + ";opacity:" + attr.opacity;

//将canvas元素添加到body元素中

    document.getElementsByTagName("body")[0].appendChild(canvas);

//该函数设置了canvas元素的width属性和height属性

    getWindowWH();

//onresize 事件会在窗口或框架被调整大小时发生

//此处即为当窗口大小改变时，重新获取窗口的宽高和设置canvas元素的宽高

    window.onresize = getWindowWH;


//该函数会得到引用了本文件的script元素，

//因为本文件中在赋值时执行了一次getScript函数，html文件引用本文件时，本文件之后的script标签还没有被浏览器解释，

//所以得到的script数组中，引用了本文的script元素在该数组的末尾

//该函数的用意为使开发者能直接修改在html中引入该文件的script元素的属性来修改画布的一些属性，画布的z-index，透明度和小圆点数量，颜色

//与前面往body元素添加canvas元素的代码配合，当开发者想要使用该特效作为背景时，只需在html文件中添加script元素并引用本文件即可

    function getAttr() {

        var scripts = document.getElementsByTagName("script"),

            len = scripts.length,

            script = scripts[len - 1];//v为最后一个script元素，即引用了本文件的script元素

        return {

            length: len,

            z: script.getAttribute("zIndex") || -1,

            opacity: script.getAttribute("opacity") || 0.5,

            color: script.getAttribute("color") || "255,255,255",

            count: script.getAttribute("count") || 200,

        }

    }

//获得窗口宽高，并设置canvas元素宽高

    function getWindowWH() {
        var scripts = document.getElementsByTagName("script"),

            len = scripts.length,

            script = scripts[len - 1];//v为最后一个script元素，即引用了本文件的script元素

        W = canvas.width = script.getAttribute("width") || window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        H = canvas.height = 400||script.getAttribute("height") || window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight

    }


//生成随机位置的小圆点

    var random = Math.random,

        squares = [];//存放小圆点


//往squares[]数组放小圆点

    for (var p = 0; p < attr.count; p++) {

        var square_x = random() * W,//横坐标

            square_y = random() * H,//纵坐标

            square_xa = 2 * random() - 1,//x轴位移 -1,1

            square_ya = 2 * random() - 1,//y轴位移

            //rgb= 'rgb('+Math.round(Math.random() * 255)+','+Math.round(Math.random() * 255)+','+Math.round(Math.random() * 255)+')';//例子颜色
            rgb= getColorRamdom();//例子颜色

        squares.push({

            x: square_x,

            y: square_y,

            xa: square_xa,

            ya: square_ya,

            max: 8000,

            rgb:rgb



        })

    }


//生成鼠标小圆点

    var mouse = {

        x: null,

        y: null,

        max: 20000

    };

//获取鼠标所在坐标

    window.onmousemove = function (i) {

//i为W3C DOM，window.event 为 IE DOM，以实现兼容IE

//不过目前似乎IE已经支持W3C DOM，我用的是IE11，我注释掉下一句代码也能实现鼠标交互效果，

//网上说7/8/9是不支持的，本人没有试验，

//当然加上是没有错的

        i = i || window.event;

        mouse.x = i.clientX;

        mouse.y = i.clientY;

    }

//鼠标移出窗口后，消除鼠标小圆点

    window.onmouseout = function () {

        mouse.x = null;

        mouse.y = null;

    }


//绘制小圆点，小圆点移动(碰到边界反向移动)，小圆点受鼠标束缚

    var animation = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (i) {

        window.setTimeout(i, 1000 / 45)

    };//各个浏览器支持的requestAnimationFrame有所不同，兼容各个浏览器


    function draw() {

//清除画布

        context.clearRect(0, 0, W, H);


        var w = [mouse].concat(squares);//连接(合并)鼠标小圆点数组和其他小圆点数组

        var x, v, A, B, z, y;


//square属性表：x，y，xa，ya，max

        squares.forEach(function (i) {


//实现小圆点定向移动

            i.x += i.xa;

            i.y += i.ya;


// 控制小圆点移动方向

// 当小圆点达到窗口边界时，反向移动

            i.xa = i.xa * (i.x > W || i.x < 0 ? -1 : 1);

            i.ya = i.ya * (i.y > H || i.y < 0 ? -1 : 1);


//fillRect前两个参数为矩形左上角的x，y坐标，后两个分别为宽度和高度

//绘制小圆点
            //context.fillStyle='rgb('+Math.round(Math.random() * 255)+','+Math.round(Math.random() * 255)+','+Math.round(Math.random() * 255)+')';
            context.fillStyle=i.rgb;
            // context.fillRect(i.x - 0.5, i.y - 0.5, 1, 1);

            context.beginPath();
            context.arc(i.x - 0.5, i.y - 0.5,1.5,0,2*Math.PI);
            context.fill();
//遍历w中所有元素

            for (var n = 0; n < w.length; n++) {

                x = w[n];

//如果x与i不是同一个对象实例且x的xy坐标存在

                if (i !== x && null !== x.x && null !== x.y) {

                    x_diff = i.x - x.x;//i和x的x坐标差

                    y_diff = i.y - x.y;//i和x的y坐标差

                    distance = x_diff * x_diff + y_diff * y_diff;//斜边平方

                    if (distance < x.max) {

//使i小圆点受鼠标小圆点束缚，即如果i小圆点与鼠标小圆点距离过大，i小圆点会被鼠标小圆点束缚,

//造成 多个小圆点以鼠标为圆心，mouse.max/2为半径绕成一圈

                        if (x === mouse && distance > x.max / 2) {

                            i.x = i.x - 0.03 * x_diff;
                            ( i.x>W)&&(i.x=parseInt(W));
                            ( i.x<0)&&(i.x=parseInt(0));
                            i.y = i.y - 0.03 * y_diff;

                            if(i.y>H-5){
                                i.y=parseInt(H)
                            }
                            if(i.y<0){
                                i.y=parseInt(0)
                            }

                        }

                        A = (x.max - distance) / x.max;

                        context.beginPath();

//设置画笔的画线的粗细与两个小圆点的距离相关，范围0-0.5，两个小圆点距离越远画线越细，达到max时画线消失

                        context.lineWidth = A / 2;

//设置画笔的画线颜色为s.c即画布颜色，透明度为(A+0.2)即两个小圆点距离越远画线越淡

                        context.strokeStyle = "rgba(" + attr.color + "," + (A + 0.2) + ")";

//设置画笔的笔触为i小圆点

                        context.moveTo(i.x, i.y);

//使画笔的笔触移动到x小圆点

                        context.lineTo(x.x, x.y);

//完成画线的绘制，即绘制连接小圆点的线

                        context.stroke();

                    }

                }

            }

//把i小圆点从w数组中去掉

//防止两个小圆点重复连线

            w.splice(w.indexOf(i), 1);

        });

//window.requestAnimationFrame与setTimeout相似，形成递归调用，

//不过window.requestAnimationFrame采用系统时间间隔，保持最佳绘制效率,提供了更好地优化，使动画更流畅

//经过浏览器优化，动画更流畅；

//窗口没激活时，动画将停止，省计算资源;

        animation(draw);

    }


//此处是等待0.1秒后，执行一次draw()，真正的动画效果是用window.requestAnimationFrame实现的

    setTimeout(function () {

        draw();

    }, 100)




}();



